<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>修改基本信息</span>
      <el-button style="float: right; padding: 3px 0" type="text" @click="showPwdContainer">修改密码</el-button>
    </div>
    <div>
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="头像">
          <ImgUpload name="user" :image-url="imageUrl" @onSuccess="onSuccess" @beforeUpload="beforeUpload" />
        </el-form-item>
        <el-form-item label="备注说明" prop="descri">
          <el-input v-model="formData.descri" type="textarea" placeholder="请输入备注说明" rows="4" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('ruleForm')">提交</el-button>
          <el-button @click="reset('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script type="text/ecmascript-6">
import ImgUpload from '@/components/ImgUpload'
import UploadMixin from '@/mixin/UploadMixin'
export default {
  components: {
    ImgUpload
  },
  mixins: [UploadMixin],
  props: {
    formData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    imageUrl() {
      if (this.formData.avatar) {
        let prefix = ''
        if (!/http:\/\/|https:\/\//.test(this.formData.avatar)) {
          prefix = `${process.env.VUE_APP_BASE_DOMAIN}`
        }
        return prefix + this.formData.avatar
      }
      return ''
    }
  },
  methods: {
    onSuccess(data) {
      this.formData.avatar = data.imgUrl
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = {
            phone: this.formData.phone,
            name: this.formData.name,
            email: this.formData.email,
            avatar: this.formData.avatar,
            descri: this.formData.descri,
            id: this.formData.id
          }
          this.$emit('submit', formData, 'changeProfile')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    reset(formName) {
      this.$refs[formName].resetFields()
    },
    showPwdContainer() {
      this.$emit('showPwdContainer')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
